package com.hsy.order.base.ui.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import com.flux.ui.activity.FBaseActivity
import com.flux.utils.BaseFileUtil
import com.flux.utils.GlideUtil
import com.flux.utils.LogUtil
import com.hsy.order.R
import java.io.File
import java.lang.ref.WeakReference

/**
 * Created on 2018/1/11.
 *
 * @author Yang
 */
class ImageSelectAdapter(activity: FBaseActivity, val data: MutableList<String>) : BaseAdapter() {

    private val mActivity: WeakReference<FBaseActivity> = WeakReference(activity)

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val holder: ViewHolder
        val view: View

        if (null == convertView) {
            holder = ViewHolder()
            view = holder.create(parent)
            view.tag = holder
        } else {
            view = convertView
            holder = view.tag as ViewHolder
        }
        holder.update(position, data[position])
        return view
    }

    fun removeData(position: Int) {
        if (position < data.size) {
            data.removeAt(position)
        }
    }

    override fun getItem(position: Int): Any? {
        return if (position < data.size) data[position] else null
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount() = data.size

    internal inner class ViewHolder {

        private lateinit var imageView: ImageView
        private lateinit var delButton: ImageView

        fun create(parent: ViewGroup): View {

            val layout = LayoutInflater.from(mActivity.get()).inflate(R.layout.image_select_item, parent, false)
            imageView = layout.findViewById(R.id.image)
            delButton = layout.findViewById(R.id.delete)

            return layout
        }

        fun update(position: Int, data: String) {
            val file = File(data)
            if (file.exists()) {
                GlideUtil.load(mActivity.get()!!, BaseFileUtil.FILE_PREFIX + data, imageView)
                imageView.setBackgroundColor(Color.TRANSPARENT)
            } else {
                imageView.setImageResource(0)
            }
            delButton.setImageResource(R.drawable.icon_upload_images_del)
            delButton.visibility = View.VISIBLE
            delButton.setOnClickListener {
                removeData(position)
                notifyDataSetChanged()
            }
        }
    }
}